/**
 * @Author: leibidong
 * @Description: 商品二级类目service层
 * @File:  secondFirstProductCategoryService
 * @Version: 1.0.0
 * @Date: 2021/7/4 20:30
 */

package service

import (
	"encoding/json"
	"fmt"
	"ginProject/biz/dao"
	"ginProject/biz/model"
	"ginProject/biz/utils"
	"ginProject/biz/vo"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

/**
 * @Author leibidong
 * @Description 查找所有的二级类目service层
 * @Date  2021/7/4 21:26
 **/
func SelectAllSecondCategory(firstName string) []model.ProductCategory {
	if len(firstName) == 0 {
		return model.SelectSecondCategoryByName(firstName)
	}
	key := utils.GetProductSecondCategory(firstName)
	rdb := dao.InitRedis()
	val2, err := rdb.Get(key).Result()
	if err == redis.Nil || err != nil {
		answer := model.SelectSecondCategoryByName(firstName)
		if answer == nil {
			return nil
		}
		var ub []byte
		ub, err := json.Marshal(answer)
		if err != nil {
			fmt.Printf("%s\n", err.Error())
		}
		rdb.Set(key, ub, 86400*time.Second)
		return answer
	}
	var val []model.ProductCategory
	_ = json.Unmarshal([]byte((val2)), &val)
	return val
}

/**
 * @Author leibidong
 * @Description 添加二级类目
 * @Date  2021/7/4 21:41
 **/
func AddSecondProductCategory(firstName, secondName string) int {
	parentId := model.QueryByName(firstName).ID
	if parentId != 0 {
		maxId := model.SelectMaxId().ID + 1
		t := utils.GetTime()
		secondCategory := model.ProductCategory{Name: secondName, Code: strconv.Itoa(maxId), ParentId: parentId, Level: 2, ModifiedTime: t, CreateTime: t}
		model.AddSecondProductCategory(secondCategory)
		key := utils.GetProductSecondCategory(firstName)
		rdb := dao.InitRedis()
		rdb.Del(key)
		return 1
	} else {
		return 0
	}
}

/**
 * @Author leibidong
 * @Description 根据用户输入二级id是否正确，来更新名称
 * @Date  2021/7/5 11:31
 **/
func UpdateSecondProductCategory(update vo.UpdateSecondName) int {
	p := model.QueryFirstNameBySecondId(update.ID)
	if len(p.Name) != 0 {
		model.UpdateSecondProductCategory(update.ID, update.NewName)
		key := utils.GetProductSecondCategory(p.Name)
		rdb := dao.InitRedis()
		rdb.Del(key)
		return 1
	} else {
		return 0
	}

}

/**
 * @Author leibidong
 * @Description 删除商品二级类目
 * @Date  2021/7/11 17:38
 **/
func DeleteSecondCategory(id int) int {
	p := model.QueryFirstNameBySecondId(id)
	if len(p.Name) != 0 {
		model.DeleteSecondCategory(id)
		key := utils.GetProductSecondCategory(p.Name)
		rdb := dao.InitRedis()
		rdb.Del(key)
		return 1
	} else {
		return 0
	}

}
